import md5 from 'js-md5'
export function signatureGenerate({ data }) {
  const secret = 'GjeH4ra$xKPd'
  const timestamp = new Date().getTime()
  data.timestamp = timestamp
  const dataStr = dataSerialize(dataSort(data))
  const str = dataStr + secret
  const sign = md5(str)
  return {
    signature: sign,
    timestamp: timestamp
  }
}

// 参数排序
function dataSort(obj) {
  if (JSON.stringify(obj) === '{}' || obj == null) {
    return {}
  }
  const key = Object.keys(obj)?.sort()
  const newObj = {}
  for (let i = 0; i < key.length; i++) {
    newObj[key[i]] = obj[key[i]]
  }
  return newObj
}

// 参数序列化
function dataSerialize(sortObj) {
  let strJoin = ''
  for (const key in sortObj) {
    strJoin += key + '=' + sortObj[key] + '&'
  }
  return strJoin
}
